/*
 * @Author: herw
 * @Date: 2020-12-15 12:24:27
 * @Last Modified by: herw
 * @Last Modified time: 2020-12-16 18:28:56
 */
<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          clearable
          size="small"
          placeholder="模糊搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation />
      </div>
      <crudOperation show :permission="permission" />
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" />
      <el-table-column prop="id" label="客户端ID" />
      <el-table-column prop="scope" label="权限" />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="authorizedGrantTypes"
        label="授权方式"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="webServerRedirectUri"
        label="回调URI"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="authorities"
        label="角色"
      />
      <el-table-column prop="accessTokenValidity" label="Token有效时间" />
      <el-table-column prop="refreshTokenValidity" label="Token刷新时间" />
      <el-table-column prop="autoapprove" label="授权">
        <template slot-scope="scope">
          <span v-if="scope.row.autoapprove === '1'">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="additionalInformation" label="备注" />
      <!--   编辑与删除   -->
      <el-table-column
        v-permission="['admin', 'client:edit', 'client:del']"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
            :disabled-edit="scope.row.id === 'moblie-client'"
            :disabled-dle="scope.row.id === 'mobile-client'"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="870px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        size="small"
        label-width="116px"
      >
        <el-form-item label="客户端名称" prop="id">
          <el-input v-model="form.id" />
        </el-form-item>
        <el-form-item label="客户端密码" prop="clientSecret">
          <el-input v-model="form.clientSecret" />
        </el-form-item>
        <el-form-item label="资源ID" prop="resourceIds">
          <el-select
            v-model="form.resourceIds"
            style="width: 185px"
            placeholder="请选择资源范围"
          >
            <el-option
              v-for="item in resourceIds"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限" prop="scope">
          <el-select
            v-model="form.scope"
            style="width: 185px"
            placeholder="请选择授权范围"
          >
            <el-option
              v-for="item in scopes"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授权方式" prop="authorizedGrantTypes">
          <el-checkbox-group v-model="form.authorizedGrantTypes" @change="changeGrantType">
            <el-checkbox v-for="item in authorizedTypes" :key="item" :label="item">{{
              item
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="回调地址" prop="webServerRedirectUri">
          <el-input v-model="form.webServerRedirectUri" style="width: 495px" />
        </el-form-item>
        <el-form-item label="Token有效时间" prop="accessTokenValidity">
          <el-input-number
            v-model.number="form.accessTokenValidity"
            :min="1"
            controls-position="right"
            style="width: 185px"
          />
        </el-form-item>
        <el-form-item label="Token刷新时间" prop="refreshTokenValidity">
          <el-input-number
            v-model.number="form.refreshTokenValidity"
            :min="1"
            controls-position="right"
            style="width: 185px"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 0" label="角色" prop="authorities">
          <el-select
            v-model="form.authorities"
            style="width: 185px"
            multiple
            placeholder="请选择"
            @remove-tag="deleteTag"
            @change="changeRole"
          >
            <el-option
              v-for="item in authorities"
              :key="item.name"
              :disabled="level !== 1 && item.level <= level"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授权" prop="autoapprove">
          <el-radio-group v-model="form.autoapprove" style="width: 178px">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="additionalInformation">
          <el-input
            v-model="form.additionalInformation"
            style="width: 380px"
            rows="5"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button
          :loading="crud.status.cu === 2"
          type="primary"
          @click="crud.submitCU"
        >确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import crudClient from '@/api/oauth/client'
import { getAll, getLevel } from '@/api/system/role'

let userRoles = []
let grantTypes = []
const defaultForm = { id: null, clientSecret: null, resourceIds: null, scope: null, authorizedGrantTypes: [], webServerRedirectUri: 'http://', accessTokenValidity: 60 * 60 * 2, refreshTokenValidity: 60 * 60 * 2, authorities: [], autoapprove: '0', additionalInformation: null }
export default {
  name: 'OauthClient',
  components: { crudOperation, rrOperation, udOperation },
  cruds() {
    return CRUD({ title: '客户端', url: 'api/client', crudMethod: { ...crudClient }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      resourceIds: ['greatwall'],
      scopes: ['read', 'write', 'read,write'],
      authorizedGrantTypes: [],
      authorizedTypes: ['authorization_code', 'password', 'implicit', 'client_credentials', 'refresh_token'],
      level: 3,
      authorities: [],
      permission: {
        add: ['admin', 'client:add'],
        edit: ['admin', 'client:edit'],
        del: ['admin', 'client:del']
      },
      rules: {
        id: [
          { required: true, message: '请输入客户端名称', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        clientSecret: [
          { required: true, message: '请输入客户端密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        resourceIds: [
          { required: true, message: '请选择资源ID', trigger: 'blur' }
        ],
        authorizedGrantTypes: [
          { required: true, message: '请选择授权方式', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initRoles = []
      userRoles.forEach(function(role, index) {
        initRoles.push(role)
      })
      crud.form.authorities = initRoles
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles()
      this.getRoleLevel()
      form.autoapprove = form.autoapprove.toString()
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      userRoles = []
      grantTypes = []

      form.authorities = form.authorities.split(',')
      form.authorizedGrantTypes = form.authorizedGrantTypes.split(',')

      form.authorities.forEach(function(role, index) {
        // 初始化编辑时候的角色
        userRoles.push(parseInt(role))
      })
      form.authorizedGrantTypes.forEach(function(type, index) {
        // 初始化编辑时候的角色
        grantTypes.push(type)
      })

      form.authorities = userRoles
      form.authorizedGrantTypes = grantTypes
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.authorities.length === 0) {
        this.$message({
          message: '角色不能为空',
          type: 'warning'
        })
        return false
      }
      crud.form.authorities = userRoles.join(',')
      crud.form.authorizedGrantTypes = grantTypes.join(',')
      return true
    },
    checkboxT(row, rowIndex) {
      return row.id !== 'mobile-client'
    },
    // 授权方式
    changeGrantType(value) {
      grantTypes = []
      value.forEach(function(data, index) {
        grantTypes.push(data)
      })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.authorities = res
      }).catch(() => { })
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => { })
    },
    changeRole(value) {
      userRoles = []
      value.forEach(function(data, index) {
        userRoles.push(data)
      })
    },
    deleteTag(value) {
      userRoles.forEach(function(data, index) {
        if (data === value) {
          userRoles.splice(index, value)
        }
      })
    }
  }
}
</script>
